package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.exception.UploadFileImageOSSException;
import com.sky.result.Result;
import com.sky.utils.AliyunOSSOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Objects;

/**
 * 通用接口
 */
@Api(tags = "通用接口")
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    /**
     * 上传文件
     * @param file
     * @return
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result upload(@ApiParam("文件") MultipartFile file) throws Exception {
        log.info("上传文件:{}", file);
        if (Objects.isNull(file) || file.isEmpty()) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.trim().isEmpty()) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        try {
            // 上传至阿里云 OSS
            String url = aliyunOSSOperator.upload(file.getBytes(), originalFilename);
            return Result.success(url);
        } catch (UploadFileImageOSSException | IOException e) {
            log.error(MessageConstant.UPLOAD_FAILED, e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
